<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :okButtonProps="{ class: {'jee-hidden': true} }"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
          <a-col :span="24" pull="6">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: 38px;width: 115%"
              label="分类名称">
              <a-input placeholder="请输入名称" v-decorator="['name', validatorRules.name]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="11" pull="1">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: 38px;width: 115%"
              label="上级分类">
              <a-select
                v-decorator="[ 'parentId', {}]"
                style="width: 100%"
                :getPopupContainer="node => node.parentNode"
                placeholder="请选择上级分类">
                <a-select-option v-for="(category,categoryIndex) in categoryList" :key="categoryIndex.toString()"
                                 :value="category.id">
                  {{ category.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="10" pull="1">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: 38px;width: 115%"
              label="分类品牌">
              <a-select
                v-decorator="[ 'brandId', validatorRules.brandId]"
                style="width: 100%"
                :getPopupContainer="node => node.parentNode"
                placeholder="请选择品牌">
                <a-select-option v-for="(brand,brandIndex) in brandList" :key="brandIndex.toString()"
                                 :value="brand.id">
                  {{ brand.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-right: -65px"
              label="排序">
              <a-input-number v-decorator="[ 'sort', {}]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-right: -65px"
              label="是否显示">
              <j-dict-select-tag v-decorator="['showStatus', {}]" placeholder="是否显示" :type="'radioButton'"
                                 :triggerChange="true" dictCode="yn"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="8">
            <a-form-item label="分类图标" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-right: -155px">
              <a-upload
                listType="picture-card"
                class="icon-uploader"
                :showUploadList="false"
                :action="uploadAction"
                :data="{'isup':1,'dir':'goods/category'}"
                :headers="headers"
                :beforeUpload="beforeUpload"
                @change="iconHandleChange"
              >
                <img v-if="iconUrl" :src="getIconView()" alt="icon" style="height:104px;max-width:300px"/>
                <div v-else>
                  <a-icon :type="uploadLoading ? 'loading' : 'plus'"/>
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col :span="16">
            <a-form-item label="分类广告" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-upload
                listType="picture-card"
                class="icon-uploader"
                :showUploadList="false"
                :action="uploadAction"
                :data="{'isup':1,'dir':'goods/category'}"
                :headers="headers"
                :beforeUpload="beforeUpload"
                @change="handleChange"
              >
                <img v-if="picUrl" :src="getPicView()" alt="icon" style="height:104px;max-width:300px"/>
                <div v-else>
                  <a-icon :type="uploadLoading ? 'loading' : 'plus'"/>
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction } from '@/api/manage'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from 'moment'
  import Vue from 'vue'
  import JDictSelectTag from '../../../components/dict/JDictSelectTag.vue'
  import JSelectMultiple from '../../../components/jeecg/JSelectMultiple'

  export default {
    name: 'PmsProductCategoryModalJX',
    components: {
      JSelectMultiple,
      JDictSelectTag
    },
    data() {
      return {
        title: '操作',
        visible: false,
        model: {},
        categoryList: [],
        brandList: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },

        confirmLoading: false,
        uploadLoading: false,
        headers: {},
        form: this.$form.createForm(this),
        validatorRules: {
          name: { rules: [{ required: true, message: '请填写分类名称!' }] },
          brandId: { rules: [{ required: true, message: '请选择品牌!' }] },
        },
        iconUrl: '',
        picUrl: '',
        url: {
          fileUpload: window._CONFIG['domianURL'] + '/sys/common/ossUpload',
          imgerver: window._CONFIG['domianURL'] + '/sys/common/view',
          add: '/pms/pmsProductCategory/add',
          edit: '/pms/pmsProductCategory/edit',
          queryLevelList: '/pms/pmsProductCategory/queryLevelList',
          getBrands: '/pms/pmsBrand/getBrands'
        }
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }
    },
    computed: {
      uploadAction: function() {
        return this.url.fileUpload
      }
    },
    methods: {
      getCategoryList(id) {
        getAction(this.url.queryLevelList, { id: id }).then(res => {
          if (res.success) {
            this.categoryList = res.result
          } else {
            console.log(res.message)
          }
        })
      },
      getBrandList() {
        getAction(this.url.getBrands, {}).then(res => {
          if (res.success) {
            this.brandList = res.result
          } else {
            console.log(res.message)
          }
        })
      },
      add() {
        this.iconUrl = ''
        this.picUrl = ''
        this.edit({ 'id': 0 })
      },
      edit(record) {
        let id = 0
        if (record) {
          id = record.id
        }
        this.getCategoryList(id)
        this.getBrandList()
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.visible = true
        this.iconUrl = this.model.icon
        this.picUrl = this.model.picUrl
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'parentId', 'brandId', 'name', 'productUnit', 'navStatus', 'showStatus', 'sort', 'keywords', 'description', 'wxQualificationFlag', 'wxCatId'))
          //时间格式化
        })
      },
      moment,
      beforeUpload: function(file) {
        var fileType = file.type
        if (fileType.indexOf('image') < 0) {
          this.$message.warning('请上传图片')
          return false
        }
        //TODO 验证文件大小
      },
      iconHandleChange(info) {
        this.iconUrl = ''
        if (info.file.status === 'uploading') {
          this.uploadLoading = true
          return
        }
        if (info.file.status === 'done') {
          var response = info.file.response
          this.uploadLoading = false
          console.log(response)
          if (response.success) {
            this.model.icon = response.message
            this.iconUrl = this.model.icon
          } else {
            this.$message.warning(response.message)
          }
        }
      },
      handleChange(info) {
        this.picUrl = ''
        if (info.file.status === 'uploading') {
          this.uploadLoading = true
          return
        }
        if (info.file.status === 'done') {
          var response = info.file.response
          this.uploadLoading = false
          console.log(response)
          if (response.success) {
            this.model.picUrl = response.message
            this.picUrl = this.model.picUrl
          } else {
            this.$message.warning(response.message)
          }
        }
      },
      getIconView() {
        if (this.model.icon !== null && this.model.icon !== undefined && this.model.icon !== '') {
          if ('http' === this.model.icon.substring(0, 4)) {
            return this.model.icon
          }
          return this.url.imgerver + '/' + this.model.icon
        }
      },
      getPicView() {
        if (this.model.picUrl !== null && this.model.picUrl !== undefined && this.model.picUrl !== '') {
          if ('http' === this.model.picUrl.substring(0, 4)) {
            return this.model.picUrl
          }
          return this.url.imgerver + '/' + this.model.picUrl
        }
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            //时间格式化

            console.log(formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
          }
        })
      },
      handleCancel() {
        this.close()
      }


    }
  }
</script>

<style lang="less" scoped>

</style>
